package cn.sxt.userscenter.common.util;

import java.util.Date;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 发送邮件的工具类
 * @author Administrator
 *
 */
@Component("springEmailUtil")
public class SpringEmailUtil {

	@Resource
	private JavaMailSender javaMailSender;
	@Resource
	private SimpleMailMessage simpleMailMessage;
	
	/**
	 * 发送邮件
	 * @param to 收件人
	 * @param subject 主题
	 * @param text 内容
	 */
	public boolean sendMail(String to,String subject,String text){
		try {
			this.simpleMailMessage.setTo(to);
			this.simpleMailMessage.setSubject(subject);
			this.simpleMailMessage.setText(text);
			this.simpleMailMessage.setSentDate(new Date());
			
			this.javaMailSender.send(simpleMailMessage);
		} catch (MailException e) {
			ConstatFinaUtil.LOGGER.error("发信失败了,收件人:{},主题:{},内容:{}",to,subject,text,e);
		}
		return false;
	}
	
	public boolean sendMailHTML(String to,String subject,String text)
	{
		try
		{
			/* 完善信的内容 */
			MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
			MimeMessageHelper mailMessage = new MimeMessageHelper(mimeMessage,"UTF-8");
			
			/* 需要强制的重新设置一下from */
			mailMessage.setFrom(this.simpleMailMessage.getFrom());
			mailMessage.setTo(to);
			mailMessage.setSubject(subject);
			/* 第二个参数表示是否是html */
			mailMessage.setText(text,true);
			mailMessage.setSentDate(new Date());
			
			/* 发送信件 */
			this.javaMailSender.send(mimeMessage);
			ConstatFinaUtil.LOGGER.info("发信成功了,收件人:{},主题:{},内容:{}",to,subject,text);
			return true ; 
		} catch (Exception e)
		{
			ConstatFinaUtil.LOGGER.error("发信失败了,收件人:{},主题:{},内容:{}",to,subject,text,e);
		}
		return false ; 
	}
}
